package im_server

import (
	"go.uber.org/zap"
	"pim/pkg/promePkg"
)

func (s *server) AddNewConn(client *ClientConn, streamID int64) {
	s.mu.Lock()
	defer s.mu.Unlock()

	// 链接计数器
	promePkg.PromeInc(promePkg.AccountConnCounter)

	pf := client.Pf
	uid := client.UserID
	logger := s.logger
	logger.Info("New User Conn ", zap.Int64("uid", uid), zap.Int("pf ", pf), zap.Int64("streamID", streamID))

	if oldConnMap, ok := s.wsUserToConn[uid]; ok {
		// 已经有这个用户了
		// TODO pf 重复判断

		findHave, isok := oldConnMap[streamID]
		if isok {
			// 推送离线事件
			findHave.KickDevice()
		}

		oldConnMap[streamID] = client
		s.wsUserToConn[uid] = oldConnMap

		logger.Info("not frist conn ", zap.Int64("uid", uid), zap.Int("pf ", pf), zap.Int64("streamID", streamID))
	} else {
		i := make(map[int64]*ClientConn)
		i[streamID] = client
		s.wsUserToConn[uid] = i
		s.logger.Debug("first conn", zap.Int64("uid", uid), zap.Int("pf", pf), zap.Int64("streamID", streamID))
	}
	if oldStringMap, ok := s.wsConnToUser[client]; ok {
		oldStringMap[streamID] = uid
		s.wsConnToUser[client] = oldStringMap
	} else {
		i := make(map[int64]int64)
		i[streamID] = uid
		s.wsConnToUser[client] = i
	}
	count := 0
	for _, v := range s.wsUserToConn {
		count = count + len(v)
	}

	s.logger.Info("WS Add operation", zap.Int("conn number ", count), zap.Int64("streamID", streamID))

}
